package com.zang.everyday;

/**
 * @Author: ZVerify
 * @Description: https://leetcode.cn/problems/reformat-phone-number/
 * @DateTime: 2022/10/1 8:20
 **/
public class 重新格式化电话号码 {
    public String reformatNumber(String number) {
        StringBuilder builder = new StringBuilder();

        // 首先将字符串中的空字符串和'-'去掉
        for (int i = 0; i <= number.length()-1; i++) {
            if (number.charAt(i)!=' '&& number.charAt(i)!='-') builder.append(number.charAt(i));
        }
        // 转成字符串
        String string = builder.toString();
        // 清空builder
        builder.delete(0,string.length());

        // 初始化指针
        int index = 0;
        int length = string.length();
        // 当前未处理的值数量大于4的时候三三分组
        while (length-index>4){
            builder.append(string, index, index+3);
            builder.append("-");
            index = index+3;
        }
        // 如果当前未处理的数量整合为4个就两两分组,否则剩下的全部为一组
        if (length-index==4){
            builder.append(string, index, index+2);

            index = index+2;
            builder.append("-");
            builder.append(string, index, index+2);
        }else {
            builder.append(string, index, length);
        }
        return builder.toString();
    }
}
